package co.yixiang.modules.quartz.task;

import co.yixiang.domain.KryConfig;
import co.yixiang.modules.shop.service.YxInvestOrderService;
import co.yixiang.modules.shop.service.dto.YxInvestOrderDto;
import co.yixiang.modules.shop.service.dto.YxInvestOrderQueryCriteria;
import co.yixiang.service.KryConfigService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 更新订单支付状态定时器
 */
@Slf4j
@Component
public class PaymentStatusUpdateTimer {
    @Autowired
    private KryConfigService kryConfigService;

    @Autowired
    private YxInvestOrderService yxInvestOrderService;

    public void run() {
        KryConfig kryConfig = kryConfigService.find();
        if (kryConfig != null) {
            YxInvestOrderQueryCriteria criteria = new YxInvestOrderQueryCriteria();
            criteria.setPaid(0);
            criteria.setPayType(2);
            List<YxInvestOrderDto> list = yxInvestOrderService.queryAll(criteria);
            if (list != null && list.size() > 0) {
                for (YxInvestOrderDto dto : list) {
                    //支付单号
                    String orderTradeNo = dto.getOrderTradeNo();
                    Map<String, Object> map = kryConfigService.payQuery(orderTradeNo);
                    if (map.get("status").equals("0")) {
                        JSONObject obj = JSON.parseObject(map.get("resultParams").toString());
                        if (0 == obj.getInteger("code")) {
                            JSONObject resultObj = JSON.parseObject(obj.getString("result"));
                            String payStatus = resultObj.getString("payStatus");
                            if ("PAYSUCCESS".equals(payStatus)) {
                                yxInvestOrderService.updatePayStatus(dto.getId(),1);
                            } else {
                                log.info("订单号:" + dto.getOrderId() + "==>" + payStatus);
                            }
                        } else {
                            log.info("订单号:" + dto.getOrderId() + "==>" + obj.getString("message"));
                        }
                    } else {
                        log.info("订单号:" + dto.getOrderId() + "==>" + map.get("errorMsg"));
                    }
                }
            }
        } else {
            log.info("未配置客如云信息");
        }
    }
}
